package ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.GastoDao;
import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.model.Gasto;
import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.model.Supervisor;

public class GastoHibernateDao implements GastoDao{

	private static SessionFactory sessionFactory = configureSessionFactory();
    private static org.hibernate.service.ServiceRegistry serviceRegistry;

      private static SessionFactory configureSessionFactory() throws HibernateException {
          Configuration configuration = new Configuration();
          configuration.configure();
          serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
          sessionFactory = configuration.buildSessionFactory(serviceRegistry);
          return sessionFactory;
      }
	
	/**
	 * Metodo que da de alta un gasto
	 * @author Daniel Solis
	 */
	@Override
	public Gasto persistir(Gasto gasto) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.saveOrUpdate(gasto);
		session.getTransaction().commit();
		session.close();
		return gasto;
	}

	@Override
	public void eliminar(Gasto gasto) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(gasto);
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Gasto> listar() {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from " + Gasto.class.getName());
		return query.list();
	}
	
	//IMPLEMENTAR
	@Override
	public List<Gasto> listarPorSupervisor(Supervisor supervisor) {
		return null;
	}

	@Override
	public Gasto buscarPorIdGasto(Integer idGasto) {
		Session session = sessionFactory.openSession();
	    return (Gasto) session.get(Gasto.class, idGasto);
	}

}
